import os
import shutil
import signal
import sys
from flask import Flask, render_template, request, send_from_directory, flash, redirect, url_for
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.secret_key = os.urandom(24)  # 用于flash消息
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def ensure_upload_dir():
    """确保上传目录存在"""
    if not os.path.exists(UPLOAD_FOLDER):
        os.makedirs(UPLOAD_FOLDER, exist_ok=True)

def cleanup_uploads():
    """清理上传目录中的所有文件"""
    ensure_upload_dir()
    # 删除目录中的所有文件
    for item in os.listdir(UPLOAD_FOLDER):
        item_path = os.path.join(UPLOAD_FOLDER, item)
        if os.path.isfile(item_path):
            try:
                os.remove(item_path)
            except Exception as e:
                print(f"无法删除文件 {item}: {e}")

def signal_handler(sig, frame):
    """处理Ctrl+C信号"""
    print("\n正在退出...")
    sys.exit(0)

# 注册信号处理器
signal.signal(signal.SIGINT, signal_handler)

@app.route('/')
def index():
    """主页路由"""
    # 确保上传目录存在
    ensure_upload_dir()
    
    # 获取文件列表
    files = os.listdir(UPLOAD_FOLDER)
    return render_template('index.html', files=files)

@app.route('/upload', methods=['POST'])
def upload_file():
    """处理文件上传"""
    if 'file' not in request.files:
        flash('没有选择文件', 'error')
        return redirect(url_for('index'))
    
    file = request.files['file']
    if file.filename == '':
        flash('没有选择文件', 'error')
        return redirect(url_for('index'))
    
    if file:
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        flash('文件上传成功！', 'success')
        return redirect(url_for('index'))

@app.route('/download/<filename>')
def download(filename):
    """处理文件下载"""
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)

if __name__ == '__main__':
    # 程序启动时，清理上传目录中的所有文件
    print("启动服务器，清理上传目录...")
    cleanup_uploads()
    
    # 获取本机IP地址
    import socket
    hostname = socket.gethostname()
    local_ip = socket.gethostbyname(hostname)
    print(f"服务器启动成功！")
    print(f"本地访问地址: http://localhost:5000")
    print(f"局域网访问地址: http://{local_ip}:5000")
    
    # 禁用自动重载功能，避免重复清理文件
    app.run(host='0.0.0.0', port=5000, debug=True, use_reloader=False) 